package com.dict.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dict.dao.DictionaryDao;
import com.util.NumUtil;

@Service
@Transactional
public class DictionaryServiceImpl implements DictionaryService {
	@Resource
	private DictionaryDao dictionaryDao;

	public void setDictionaryDao(DictionaryDao dictionaryDao) {
		this.dictionaryDao = dictionaryDao;
	}
	
	private void addState(List<Map<String, Object>> data) {
		for (Map<String, Object> i : data) {
			String state = "open";
			if (hasChild((Integer)i.get("id"))) {
				state = "closed";
			}
			i.put("state", state);
		}
	}

	@Override
	public List<Map<String, Object>> getItems(int page, int rows) {
		List<Map<String, Object>> data = dictionaryDao.getDictionary(page, rows);
		addState(data);
		return data;
	}

	@Override
	public List<Map<String, Object>> getItemByPid(int pid) {
		List<Map<String, Object>> data = dictionaryDao.getDictionaryChild(pid);
		addState(data);
		return data;
	}

	@Override
	public boolean hasChild(int id) {		
		return dictionaryDao.hasChild(id);
	}

	@Override
	public int getRows() {		
		return dictionaryDao.getRows();
	}

//	@Override
//	public Map<String, Object> getItemByName(String name) {
//		return null;
//	}

	@Override
	public Map<String, Object> addItem(Map<String, String> item) {
		if (dictionaryDao.isExist(item.get("name"))) {
			return null;
		}
		return dictionaryDao.saveDictionary(item);
	}

	@Override
	public Map<String, Object> updateItem(Map<String, String> item) {
		String id = item.get("id");
		if (id == null || !dictionaryDao.isExist(NumUtil.parseInt(id, 0))) {
			return null;
		}
		return dictionaryDao.updateDictionary(item);
	}

	@Override
	public boolean removeItem(String id) {
		int i = NumUtil.parseInt(id, -1);
		if (i == -1) {
			return false;
		}
		return dictionaryDao.removeDictionaryTree(i).size() > 0;
	}
	
	private boolean isValid(String name) {
		String[] keys = {"name", "value", "remark"};		
		for (String i : keys) {
			if (i.equals(name)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public List<Map<String, Object>> searchItem(String name, String value) {
		if (!isValid(name)) {
			return null;
		}
		
		return dictionaryDao.getDictionary(name, value);
	}

	@Override
	public List<Map<String, Object>> moveUp(int id, String path, int sort) {
		if (path.equals(";0;") || sort == 1) {
			return null;
		}
		
		return dictionaryDao.moveUp(id, path, sort);
	}

	@Override
	public List<Map<String, Object>> moveDown(int id, String path, int sort) {
		if (path.equals(";0;")) {
			return null;
		}
		
		return dictionaryDao.moveDown(id, path, sort);
	}

}
